package cn.xmall.services.cn.xmall.services.impl;

import cn.xmall.caches.UserCache;
import cn.xmall.mappers.UserMapper;
import cn.xmall.models.User;
import cn.xmall.models.UserExample;
import cn.xmall.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

/**
 * Created by MoTaiXian on 2017/7/17.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    UserCache userCache;

    @Override
    public User getByUserName(String userName) throws Exception {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria= userExample.createCriteria();
        criteria.andUsernameEqualTo(userName);
        List<User> list=userMapper.selectByExample(userExample);
        if(list!=null && list.size()>0)
            return list.get(0);
        return null;
    }

    @Override
    public User getByPhone(String phone) throws Exception {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andPhoneEqualTo(phone);
        List<User> list=userMapper.selectByExample(userExample);
        if(list!=null && list.size()>0)
            return list.get(0);
        return null;
    }

    @Override
    @Transactional
    public void registerUser(User user) throws Exception{
        if(isRegisteredUser(user)){
            throw new UserServiceException("illegal user");
        }

        Assert.notNull(user.getPassword(),"user password is null");
        String passWordMD5Hex=DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(passWordMD5Hex);
        user.setUpdated(new Date());
        user.setCreated(new Date());

        userMapper.insert(user);
    }

    @Override
    public String loginUser(String userName, String passWord) throws Exception {
        Assert.notNull(userName,"userName is null");
        Assert.notNull(passWord,"passWord is null");

        User user=getByUserName(userName);
        //用户名存在
        if(user==null){
            return null;
        }

        //密码正确
        String passWordMD5Hex=DigestUtils.md5DigestAsHex(passWord.getBytes());
        if(!passWordMD5Hex.equals(user.getPassword())){
            return null;
        }

        //用户密码置空
        user.setPassword("");

        String token= UUID.randomUUID().toString();
        userCache.save(token,user);

        return token;
    }

    @Override
    @Transactional
    public void changePassWord(String token, String passWord) throws Exception {
        Assert.notNull(token,"token is null");
        Assert.notNull(passWord,"passWord is null");

        User user= getLoggedInUserByToken(token);
        Assert.notNull(user,"user is null");
        Assert.notNull(user.getUsername(),"user name is null");

        String md5Str=DigestUtils.md5DigestAsHex(passWord.getBytes());
        user.setPassword(md5Str);

        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        userMapper.updateByExampleSelective(user,userExample);
    }

    @Override
    // TODO: 2017/7/18
    public void updateUserInfo(String token,User user) throws Exception {

    }


    @Override
    public User getLoggedInUserByToken(String token) throws Exception{
        User user=userCache.getByTokenKey(token);
        if(user!=null){
            return user;
        }

        return null;
    }

    public boolean isRegisteredUser(User user) throws UserServiceException {
        try{
            Assert.notNull(user,"user is null");
            Assert.notNull(user.getUsername(),"user name is null");
            Assert.notNull(user.getPhone(),"user phone is null");

            if(isRegisteredUserName(user.getUsername())
                    || isRegisterdPhoneNum(user.getPhone())){
                return true;
            }
        }catch (Exception e){
            throw new UserServiceException("isRegisteredUser "+e.getMessage(),e);
        }

        return false;

    }

    public boolean isRegisteredUserName(String name) throws Exception {
        User user=getByUserName(name);
        if(user!=null){
            return true;
        }
        return false;
    }

    public boolean isRegisterdPhoneNum(String phoneNum) throws Exception {
        User user=getByPhone(phoneNum);
        if(user!=null){
            return true;
        }
        return false;
    }

}
